<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
namespace Agp\CoreBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\DependencyInjection\Container;
use JMS\DiExtraBundle\Annotation\Validator;
use JMS\DiExtraBundle\Annotation\InjectParams;
use JMS\DiExtraBundle\Annotation\Inject;

/**
 * Description of RepasseVlrAntecipadoValidator
 *
 * @author bondcs
 * @Validator("repasse_vlr_antecipado")
 */
class RepasseVlrAntecipadoValidator extends ConstraintValidator {
    
    protected $container;
    protected $user;

    /**
     * @InjectParams({
     *      "container" = @inject("service_container")
     * })
     * 
     * @param \Symfony\Component\DependencyInjection\Container $containeir
     */
    public function __construct(Container $container) {
        $this->container = $container;
    }

    public function validate($repasse, Constraint $constraint) {
        
        $user = $this->container->get('security.context')->getToken()->getUser();
        $utils = $this->container->get('admin.utils');
        
        if ($repasse->getEvento() == null){
            $totalVenda = $this->container->get('agp.itemVenda.repository')->getTotalVendasBarRepasse($repasse->getEmpresa());
        }else{
            $totalVenda = $this->container->get('agp.itemVenda.repository')->getTotalVendasByEvento($repasse->getEvento());
        }

        $totalRepasse = $this->container->get('agp.repasse.repository')->getRepasseEvento($repasse->getEvento());
        $saldo = $utils->floordec($totalVenda['vlrAntecipacao']) - $totalRepasse['vlrAntecipado'];
        $saldoString = "R$ ".number_format($saldo, 2, ',','.');

        if ($repasse->getCodRepasse() != null){
            $em = $this->container->get('doctrine')->getEntityManager('default');
            $previousRepasse = $em->getRepository('AgpCoreBundle:Repasse')->findOneBy(array('codRepasse' => $repasse->getCodRepasse()));
            $uow = $em->getUnitOfWork();
            $uow->computeChangeSets();
            $changeset = $uow->getEntityChangeSet($previousRepasse);
            $saldo += $changeset['vlrAntecipado'][0]; 

        }
        
        if ($repasse->getVlr() <= 0 AND $repasse->getVlrAntecipado() <= 0){
               $this->context->addViolation("Não pode retirar zero");
        }
        
        if ($repasse->getVlrAntecipado() > $saldo){
               $this->context->addViolation($constraint->message, array('%string%' => $saldoString, '%evento%' => ($repasse->getEvento() == null ? 'TRANSAÇÃO BAR' : $repasse->getEvento()->getInfo()->getDescricao())));
        }
    }
}

?>
